<template>
    <div>
        <a-modal
            :title="versionInfo.id ? '编辑支线版本' : '新增支线版本'"
            centered
            v-model:visible="visible"
            :confirm-loading="loading"
            :width="600"
            okText="确认"
            @ok="handleSave"
            @cancel="handleCancel"
        >
            <a-form ref="ruleFormRef" layout="inline" :model="form" :rules="rules">
                <a-row>
                    <a-col :span="24">
                        <a-form-item label="PBI目录" name="catalogCode">
                            <span>
                                {{ pbiName }}
                            </span>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24" v-if="lubiaoDetail.pmpRegisteredProjectDTO">
                        <a-form-item label="上级版本">
                            <span v-if="lubiaoDetail.pmpRegisteredProjectDTO.pmpVersionManagementDTO">
                                {{ lubiaoDetail.pmpRegisteredProjectDTO.pmpVersionManagementDTO.versionNumber }}
                            </span>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="版本号" :span="24" name="versionNumber" class="version-number-form-item">
                            <div>
                                <VersionNumberInput
                                    :lubiaoDetail="lubiaoDetail"
                                    ref="versionNumberInputRef"
                                    :versionInfo="versionInfo"
                                    v-if="visible"
                                />
                            </div>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </a-modal>
    </div>
</template>

<script lang="ts">
import api from '@/api';
import VersionNumberInput from './VersionNumberInput.vue';
import { transformDataByFlatProperty } from '@/utils/tree';
import { deepClone } from '@/utils/util';
import { message } from 'ant-design-vue';
import { treeFilter } from '@/utils/tree';
import { defineComponent, ref, unref, reactive, toRefs, onDeactivated, nextTick } from 'vue';
export default defineComponent({
    components: {
        VersionNumberInput
    },
    props: {
        lubiaoDetail: {
            type: Object,
            default: () => ({})
        }
    },
    emits: ['success'],
    setup(props, { emit }) {
        const ruleFormRef = ref<any>();
        const versionNumberInputRef = ref<any>();
        const state = reactive<any>({
            form: {
                versionNumber: '',
                parentId: ''
            },
            visible: false,
            loading: false,
            pbiName: '',
            versionInfo: {
                type: '2'
            }
        });
        const validateVersionNumber = async () => {
            const res = await unref(versionNumberInputRef).validate();
            return !res ? Promise.reject('') : Promise.resolve();
        };
        const rules = {
            versionNumber: [{ validator: validateVersionNumber, trigger: 'change' }]
        };
        const open = (versionInfo) => {
            state.versionInfo = versionInfo || {
                type: '2'
            };
            if (props.lubiaoDetail.pmpRegisteredProjectDTO) {
                if (
                    props.lubiaoDetail.pmpRegisteredProjectDTO.pmpVersionManagementDTO &&
                    props.lubiaoDetail.pmpRegisteredProjectDTO.pmpVersionManagementDTO.id
                ) {
                    state.form.parentId = props.lubiaoDetail.pmpRegisteredProjectDTO.pmpVersionManagementDTO.id;
                }
            }
            getPbiTreeData();
            state.visible = true;
            nextTick(() => {
                unref(ruleFormRef) && unref(ruleFormRef).clearValidate();
            });
        };
        const handleSelectChange = (val) => {
            state.list = [...val];
        };
        // 新增支线版本号
        const handleSave = async () => {
            unref(ruleFormRef)
                .validate()
                .then(async () => {
                    state.form.versionNumber = unref(versionNumberInputRef).versionNumber;
                    const query = {
                        ...state.versionInfo,
                        id: state.versionInfo.id || null,
                        ...state.form,
                        type: '2',
                        catalogCode: props.lubiaoDetail.catalogCode
                    };
                    const { success, errorMsg, moule } = await api.versionControlModel.save(query);
                    if (success) {
                        message.success(state.versionInfo.id ? '编辑成功' : '新增成功');
                        // 新增的需要立即关联路标
                        if (!state.versionInfo.id && moule.id) {
                            handleBatch(moule.id);
                        } else {
                            state.visible = false;
                            emit('success');
                        }
                    } else {
                        message.error(errorMsg);
                    }
                });
        };
        // 关联支线版本
        const handleBatch = async (verMgtId) => {
            const query = {
                ...props.lubiaoDetail,
                verMgtId
            };
            const { success, errorMsg } = await api.signpostModel.save(query);
            if (success) {
                state.visible = false;
                emit('success');
            } else {
                message.error(errorMsg);
            }
        };
        // 获取所有pbi数据
        const getPbiTreeData = async () => {
            const query = {
                type: 2
            };
            const { success, moule } = await api.portalControlModel.getSystemProductCatalogTreeData(query);
            if (success) {
                if (moule) {
                    state.pbiTreeData = transformDataByFlatProperty(deepClone(JSON.parse(moule)));
                    const target = treeFilter(state.pbiTreeData, (node) => node.catalogCode === props.lubiaoDetail.catalogCode);
                    state.pbiName = getPbiName(target, '');
                }
            }
        };
        const getPbiName = (target, name) => {
            if (target && target.length) {
                if (name) {
                    name = `${name} / ${target[0].catalogName}`;
                } else {
                    name = target[0].catalogName;
                }
                return getPbiName(target[0].subNodes, name);
            }
            return name;
        };
        const handleCancel = () => {
            state.visible = false;
        };
        // 销毁时关闭弹窗
        onDeactivated(() => {
            state.visible = false;
        });
        return {
            ruleFormRef,
            versionNumberInputRef,
            ...toRefs(state),
            rules,
            open,
            handleSelectChange,
            handleSave,
            handleCancel
        };
    }
});
</script>

<style scoped lang="less">
::v-deep(.version-number-form-item) {
    .ant-form-item-explain-error {
        display: none;
    }
}
</style>